<?php

namespace App\Admin\Controllers;

use App\Models\CaseContract;
use App\Admin\Traits\Customfields;
use Carbon\Carbon;
use App\Admin\Renderable\CaseCustomerTable;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Admin;
use App\Models\CaseCustomer;
use App\Admin\Traits\Exportfields;
use Illuminate\Http\Request;

class CaseContractController extends AdminController
{
    use Customfields, Exportfields;
    public static $css = [
        '/static/css/contract_show.css',
    ];
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        // dd(date("Y-m-d", strtotime("-7 day")));

        if (!Admin::user()->isRole('administrator')) {
            $contract = CaseContract::whereHas('caseCustomer', function ($query) {
                $query->where('admin_user_id', Admin::user()->id);
            });
        } else {
            $contract = new  CaseContract();
        }

        return Grid::make($contract, function (Grid $grid) {
            $grid->showColumnSelector();
            $grid->selector(function (Grid\Tools\Selector $selector) {
                $selector->select('status', '状态', ['执行中', '终止执行'], function ($query, $value) {
                    $between = ['>=','<'];

                    $value = current($value);
                    $query->where('expiretime', $between[$value] ,Carbon::now());
                });
                $selector->select('signdate', '签订日期', ['3天内', '7天内', '15天内', '1月内', '2月内'], function ($query, $value) {
                    $between = [
                        [date("Y-m-d", strtotime("-3 day")), date("Y-m-d")],
                        [date("Y-m-d", strtotime("-7 day")), date("Y-m-d")],
                        [date("Y-m-d", strtotime("-15 day")), date("Y-m-d")],
                        [date("Y-m-d", strtotime("-1 month")), date("Y-m-d")],
                        [date("Y-m-d", strtotime("-2 month")), date("Y-m-d")],
                    ];

                    $value = current($value);
                    $query->whereBetween('signdate', $between[$value]);
                });
                $selector->select('expiretime', '到期时间', ['3天内', '7天内', '15天内', '1月内', '2月内'], function ($query, $value) {
                    $between = [
                        [date("Y-m-d"), date("Y-m-d", strtotime("+3 day"))],
                        [date("Y-m-d"), date("Y-m-d", strtotime("+7 day"))],
                        [date("Y-m-d"), date("Y-m-d", strtotime("+15 day"))],
                        [date("Y-m-d"), date("Y-m-d", strtotime("+1 month"))],
                        [date("Y-m-d"), date("Y-m-d", strtotime("+2 month"))],
                    ];

                    $value = current($value);
                    $query->where('expiretime', $between[$value]);
                });
            });

            $grid->status('状态')->display(function ($id) {
                if(Carbon::now() < $this->signdate){
                    $status = 0;
                }elseif (Carbon::now() > $this->expiretime) {
                    $status = 2;
                }else {
                    $status = 1;
                }
                return $status;
            })->using(
                [
                    0 => '<span class="badge badge-primary">未开始</span>',
                    1 => '<span class="badge badge-success">执行中</span>',
                    2 => '<span class="badge badge-danger">已结束</span>',
                ]
            );

            $grid->title->link(function () {
                return admin_url('casecontracts/' . $this->id);
            });
            $grid->case_customer_id('所属客户')->display(function ($id) {
                return optional(CaseCustomer::find($id))->name;
            });
            $grid->signdate->sortable();
            $grid->expiretime->sortable();
            // $grid->total;
            $this->gridfield($grid, 'contract');
            if (Admin::user()->isRole('administrator')) {
                // 导出
                $this->Exportfield($grid, 'contract');
            }

            $grid->model()->orderBy('id', 'desc');
            $grid->disableBatchActions();
            $grid->disableRefreshButton();
            $grid->toolsWithOutline(false);
            $grid->disableFilterButton();
            $grid->quickSearch('id', 'title');
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                // 生成合同
                $actions->append('<a href="' . admin_route('buildContracts.index', ['contract_id' => $this->id]) . '"><i class="feather icon-file-text"></i> 生成合同</a>');
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */

    public function show($id, Content $content)
    {
        Admin::css(static::$css);
        $detalling = Admin::user()->id != CaseContract::find($id)->caseCustomer->adminUser->id;
        $Role = !Admin::user()->isRole('administrator');
        if ($Role && $detalling) {
            $Contract = CaseContract::find($id);
            $this->authorize('update', $Contract);
        }

        $contract = CaseContract::with(['caseCustomer','caseCustomer.caseContacts','caseBatchs','caseCases','caseReceipts', 'caseEvents' => function ($q) {
            $q->orderBy('updated_at', 'desc');
        }, 'caseEvents.caseContact', 'caseEvents.adminUser', 'Attachments'])->findorFail($id);


        $data = [
            'contract'       => $contract,
            'contacts'       => $contract->caseCustomer->caseContacts,
            'customer'       => $contract->caseCustomer,
            'receipts'       => $contract->caseReceipts,
            'cases'       => $contract->caseCases,
            'events'         => $contract->caseEvents,
            'adminUser'     => $contract->caseCustomer->adminUser,
            'attachments'    => $contract->Attachments,
            'contractfields' => $this->custommodel('contract'),
        ];
        return $content
            ->title('合同')
            ->description('详情')
            ->body($this->_detail($data));
    }
    private function _detail($data)
    {
        return view('admin/contract/show', $data);
    }



    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new CaseContract(), function (Form $form) {
            // $Editing = $form->isEditing() && Admin::user()->id != CrmCustomer::find($form->model()->customer_id)->admin_user_id;
            // if ($Editing) {
            //     $customer = CrmCustomer::find($form->model()->id);
            //     $this->authorize('update', $customer);
            // }

            Admin::css(static::$css);
            $form->column(6, function (Form $form) {
                $form->hidden('id');
                $form->text('title');
            });
            $form->column(6, function (Form $form) {

                $form->selectTable('case_customer_id')
                    ->title('选择所属客户')
                    ->dialogWidth('50%') // 弹窗宽度，默认 800px
                    ->from(CaseCustomerTable::make(['id' => $form->getKey()])) // 设置渲染类实例，并传递自定义参数
                    ->model(CaseCustomer::class, 'id', 'name'); // 设置编辑数据显示
            });
            $form->column(6, function (Form $form) {
                $form->date('signdate', '签署时间')->required();
            });


            $form->column(6, function (Form $form) {
                $form->date('expiretime', '到期时间')->required();
            });

            //            $form->column(6, function (Form $form) {
            //                $form->currency('total', '合同金额')->symbol('￥')->attribute('min', 0)->default(0);
            //            });
            //
            //            $form->column(6, function (Form $form) {
            //                $form->currency('salesexpenses', '商务费用')->symbol('￥')->attribute('min', 0)->default(0);
            //            });
            # 商务费用 由支出动态添加所得
            $form->column(12, function (Form $form) {
                $form->currency('total', '合同金额')->symbol('￥');
        });

            $form->column(12, function (Form $form) {
                $form->hidden('salesexpenses')->default(0);
                $form->textarea('remark', '备注');
                $this->formfield($form, 'contract');
                $form->hidden('fields')->value(null);
            });

            $form->column(12, function (Form $form) {
                $form->table('compliance', '履约步骤', function ($table) {
                    $table->date('date', '时间节点');
                    $table->text('content', '履约内容');
                    $table->currency('receipt', '收款')->symbol('￥');
                    // $table->switch('isend','是否完成');
                })->saving(function ($v) {
                    return json_encode($v);
                });
            });

            $class = $this;
            $form->saving(function (Form $form) use ($class) {
                //                if ($form->salesexpenses || $form->total) {
                //                    $form->salesexpenses = str_replace(',', '', $form->salesexpenses);
                //                    $form->total = str_replace(',', '', $form->total);
                //                }
                if(!$form->total){
                    $form->total = 0;
                }
                $form_field = array();
                foreach ($class->custommodel('Contract') as $field) {
                    $field_field = $field['field'];
                    $form_field[$field_field] = $form->$field_field;
                    $form->deleteInput($field['field']);
                }
                // dd(json_encode($form_field));
                $form->fields = json_encode($form_field);

                return $form;
            });
            // $form->saved(function (Form $form, $result) {
            //     if ($form->isCreating()) {
            //         $new_contract_id = $result;
            //         if (!$new_contract_id) {
            //             return $form->error('合同新增失败');
            //         }
            //         $contract = CaseContract::find($new_contract_id);
            //         foreach ($contract->caseOrders as $order) {
            //             $contract->total += abs($order->executionprice * $order->quantity);
            //             # 快照标准价
            //             $order->prod_price = $order->caseProduct->price;
            //             $order->save();
            //         }
            //         $contract->save();
            //     }
            // });
        });
    }


    protected function nodes(CaseContract $id, Request $request)
    {
        $request->validate([
            'nodes' => 'required|max:1)'
        ]);
        $id->update([
            'nodes' => $request->nodes,
        ]);
        admin_toastr('履约进度更新成功', 'success');
        return redirect()->back();
    }
}
